/******************************************************************************
 * Author:      671643387
 * Created:     2016/9/29               winpercent: parseInt(((user.marks.wingame / user.marks.totalgame) * 100 ) % 1),
 *****************************************************************************/

var mUtil = require('./util.js');
var mFunc = require('./function.js');
var ErrorCodes = require('./error.js').ErrorCodes;
var mjMark = require('./mjmark.js');
///////////////////////////////////////////////////////////////////////////////

var MAX_CARDS = 13;

/**
 * 玩家手牌
 * @constructor
 */
function HandCards() {
    this.num = 0;           // 当前牌总数
    this.cards = [];        // 玩家手牌

    this.init();
}
HandCards.prototype = {
    // 初始化
    init: function() {
        for (var iCard = 0; iCard < MAX_CARDS; ++iCard) {
            var value = iCard + 3;
            //A 和 2 放最后面，
            if(iCard == 11){
                value = 1;
            }else if(iCard == 12){
                value = 2;
            }
            this.cards[iCard] = {
                type: value,
                num: 0,
                red: 0,
                black: 0,
                block: 0,
                plum: 0,
            };
        }
        this.num = 0;
    },

    // 添加手牌
    adds: function(cards,flag) {
        var _me = this;
         
        cards.forEach(function(card){
            //A 和 2 放最后面，
            var pos = card.type - 3;
            if(card.type == 1){
                pos = 11;
            }else if(card.type == 2){
                pos = 12;
            }

            if(card.value == 1){
                _me.cards[pos].red = 1;
                _me.cards[pos].num += 1;
            }else if(card.value == 2){
                _me.cards[pos].black = 1;
                _me.cards[pos].num += 1;
            }else if(card.value == 3){
                _me.cards[pos].block = 1;
                _me.cards[pos].num += 1;
            }else if(card.value == 4){
                _me.cards[pos].plum = 1;
                _me.cards[pos].num += 1;
            }
            _me.num += 1;
        });
    },

    // 减少手牌
    decCard: function(cards) {
        var _me = this;
        var pokers =  _me.cards;
        cards.forEach(function (card) {
            var pos = card.type - 3;
            if(card.type == 1){
                pos = 11;
            }else if(card.type == 2){
                pos = 12;
            }

            if(card.red) {
                pokers[pos].red = 0;
                pokers[pos].num -= 1;
                _me.num -= 1;
            }
            if(card.black) {
                pokers[pos].black = 0;
                pokers[pos].num -= 1;
                _me.num -= 1;
            }
            if(card.block){
                pokers[pos].block = 0;
                pokers[pos].num -= 1;
                _me.num -= 1;
            }
            if(card.plum){
                pokers[pos].plum = 0;
                pokers[pos].num -= 1;
                _me.num -= 1;
            }
        });
    },

    // 手牌是否有这个花色的牌
    hasSameColor: function(numCard) {
        var flag = false;
        for (var index in this.cards) {
            if(!this.cards.hasOwnProperty(index)){
                flag = false;
                continue;
            }
            var card = this.cards[index];

            if ( card.type != numCard.type || card.num < 1 ) {
                continue;
            }

            if ( numCard.value == 1 && card.red != 0 ) {
                flag = true;
                break;
            } else if ( numCard.value == 2 && card.black != 0 ) {
                flag = true;
                break;
            } else if ( numCard.value == 3 && card.block != 0 ) {
                flag = true;
                break;
            } else if ( numCard.value == 4 && card.plum != 0 ) {
                flag = true;
                break;
            } else {
            }
        }
        return flag;
    },

    // 手牌是否有这个字面值的牌
    hasSameCard: function(iCard) {
        var flag = false;
        this.cards.forEach(function ( card ) {
            if ( card.type == iCard && card.num > 0) {
                flag = true;
            }
        });

        return flag;
    },

    // 获取手牌同步数据
    getSyncData: function() {
        return this.cards;
    },

    // 获取还剩余几张手牌
    getRemainCardNum: function() {
        return this.num;
    },

    // 获取剩余的卡片
    getRemainCards: function() {
        var cards = [];
        this.cards.forEach(function(card){
            if (card.num != 0) {
                cards.push(card);
            }
        });
        return cards;
    },
};

/**
 * 扑克玩家
 * @constructor
 */
function Player(owner) {
    this.owner          = owner;      // 玩家所在房间
    this.uid            = 0;          // 玩家编号
    this.integral       = 0;          // 玩家积分
    this.tempIntegarl   = 0;          // 当前局积分
    this.conn           = null;       // 连接对象
    this.isThisClose    = false;
    this.ip             = "";         // 玩家IP
    this.player         = null;       // 玩家信息
    this.handsPokers    = new HandCards();// 玩家手牌
    this.totalBomb      = 0;          // 出炸弹的总次数
    this.totalCoverBomb = 0;          // 被炸的总次数
    this.totalCatchPock = 0;          // 捉麻子总次数
    this.totalCoverCatchPock = 0;     // 被捉麻子总次数
    this.totalSurplusCardNum = 0;     // 总剩余牌数量

    this.online         = false;      // 是否在线
    this.hangPackets    = [];         // 挂起等待发送的数据包

    this.marks          = [];         // 标志
    this.isNullBomb     = false;      // 是否空炸
    this.isNotUseBomb   = false;      // 玩家是否不能使用炸弹
    this.isDischargeWater= false;     // 玩家是否作弊
    this.tempScore      = 0;          // 当前局牌分数
    this.tmepdischargeWaterNum = 0;   // 放水积分
    this.isOffTwo       = false;      // 是否有关2
}
Player.prototype = {

    /**
     * 初始化玩家数据
     * @param conn      连接对象
     * @param uid       玩家编号
     * @param player    玩家数据
     */
    init: function(conn, uid, player) {
        this.uid = uid;
        this.conn = conn;
        this.player = player;

        // 扑克玩家
        this.conn.player = this;
        this.ip = this.conn.remoteAddress;

        // 设置玩家在线
        this.online = true;
    },

    // 玩家继续下一局，重置数据
    continue: function() {
        this.handsPokers.init();
        this.marks = [];

        this.tempScore = 0;
        this.isNotUseBomb = false;
        this.isDischargeWater = false;
        this.tempIntegarl = 0;
        this.bombIntegarl = 0;
        this.isOffTwo = false;
        this.tmepdischargeWaterNum = 0;
        this.isNullBomb = false;
    },

    // 获取同步数据
    getSyncData: function(mini) {
        var syncData = {};
        var _me = this;
        if (mini) {
            var handsPokers = _me.handsPokers.getSyncData();
            var cardNum = _me.handsPokers.getRemainCardNum();
            if(!cardNum){
                handsPokers = [];
            }

            syncData = {
                info: _me.getInfo(),        // 玩家名字，头像等数据
                integral: _me.integral,     // 当前分数
                cards: handsPokers,                   // 手牌
                cardNum: cardNum,                   // 剩余手牌张数
                isNotBomb: _me.getNotUseBomb(),         // 玩家能否使用炸弹
            };
        } else {
            syncData = {
                info: _me.getInfo(),           // 玩家名字，头像等数据
                integral: _me.integral,        // 当前分数
                cards: [],             // 手牌
                cardNum: 0,                // 剩余手牌张数
                isNotBomb: false,         // 玩家能否使用炸弹
            };
        }

        return syncData;
    },

    // 该玩家断线了
    onDisconnect: function() {
        this.online = false;
        if(this.owner){
            //  不是自己请求断开的
            if(!this.isThisClose) {
                this.owner.onPlayerDisconnect( this );
            }else{
                //  自己请求断开不发离线消息
                this.isThisClose = false;
            }
        }
    },

    // 玩家重连
    onReconnect: function() {
        // 发送缓存的数据包给该玩家
        if (this.hangPackets.length > 0) {
            this.hangPackets.forEach(function(packet){
                this.sendPacket(packet.act, packet.msg);
            }.bind(this));
            this.hangPackets = [];
        }
    },

    isOnline: function() {
        return this.online;
    },

    decIntegral: function(num) {
        this.integral -= num;
        this.tempIntegarl -= num;
    },
    incIntegral: function(num) {
        this.integral += num;
        this.tempIntegarl += num;
    },

    getSettlementInfo: function(creatorId) {
        return {
            userInfo: this.player,
            isCreateRoom: creatorId == this.uid,
            integral: this.integral,
            tempintegarl:this.tempIntegarl,
            cards: this.handsPokers,
            bombIntegarl: this.bombIntegarl,
            dischargeWaterNum:this.tmepdischargeWaterNum,
            isOffTwo: this.getIsOffTwo(),
            totalBomb:this.totalBomb     ,// 出炸弹的总次数
            totalCoverBomb:this.totalCoverBomb,// 被炸的总次数
            totalCatchPock:this.totalCatchPock,// 捉麻子总次数
            totalCoverCatchPock:this.totalCoverCatchPock,// 被捉麻子总次数
            totalSurplusCardNum:this.totalSurplusCardNum,// 总剩余牌数量
        };
    },

    /**
     * 这个数据是否已经初始化
     */
    isInited: function () {
        return this.player != null;
    },

    isPlayer: function(uid) {
        return this.uid == uid;
    },

    /**
     * 设置手牌
     * @param cards
     */
    setCards: function(cards,flag) {
        var myThis = this;
        myThis.handsPokers.adds(cards, flag);
        myThis.sendPacket('setCards', {
            "cards":myThis.handsPokers.getSyncData(),
            "num": myThis.handsPokers.num
        });
    },
    setBombIntegral: function(integral){
        this.bombIntegarl += integral;
    },
    setCoverBombIntegral: function(integral){
        this.bombIntegarl -= integral;
    },
    setAddTotalBomb: function(){
        this.totalBomb += 1;
    },
    setAddTotalCoverBomb: function () {
        this.totalCoverBomb += 1;
    },
    setAddTotalCatchPock: function(){
        this.totalCatchPock += 1;
    },
    setAddTotalCoverCatchPock: function () {
        this.totalCoverCatchPock += 1;
    },
    setAddTotalSurplusCardNum: function (num) {
        this.totalSurplusCardNum += num;
    },
    setAddTmepdischargeWaterNum : function ( num ) {
        this.tmepdischargeWaterNum -= num;
    },
    setNotUseBomb: function ( flag ) {
        this.isNotUseBomb =  flag;
    },
    getNotUseBomb: function () {
        return this.isNotUseBomb;
    },
    setIsNullBomb: function ( flag ) {
        this.isNullBomb = flag;
    },
    getIsNullBomb: function (  ) {
        return this.isNullBomb;
    },
    setIsOffTwo: function ( flag ) {
        this.isOffTwo  = flag;
    },
    getIsOffTwo: function (  ) {
        return this.isOffTwo;
    },
    setTempScore: function ( num ) {
        this.tempScore +=  num;
    },
    setPlayerIsDischargeWater: function ( flag ) {
        this.isDischargeWater = flag;
    },
    setPushMarks: function(flag){
        this.marks.push(flag);
    },
    getMarks: function(){
        return this.marks;
    },

    /**
     * 玩家出牌
     * @param card
     * @returns {boolean}
     */
    playCard: function(cards) {
        if(!cards || cards.num == 0){
            return false;
        }
        //减掉手牌
        this.handsPokers.decCard(cards.cards);

        return true;
    },


    ///////////////////////////////////////////////////////////////////////////
    //>> 功能函数

    // 发送数据包
    sendPacket: function(act, content) {
        if (!this.online) {
            // 玩家不在线时将推送给他的数据缓存起来等待发送
            this.hangPackets.push({
                act: act,
                msg: content,
            });

            return;
        }

        var resp = {
            code: 0,
            desc: '',
            mod: 'api',
            act: act,
            data: content
        };
        if(act != "setTipMsg") {
            DEBUG( util.format( "Send %s to %d, %j", act, this.uid, content ) );
        }
        this.conn.sendUTF(JSON.stringify(resp));
    },

    // 返回给其他玩家展示的数据
    getInfo: function() {
        if (!this.player) {
            return this.player;
        }

        var info = clone(this.player);
        info.uid = this.uid;
        info.ip = this.ip;
        return info;
    },
    exit: function() {
        this.conn.close();
        this.isThisClose = true;
        this.uid            = 0;          // 玩家编号
        this.integral       = 0;          // 玩家积分
        this.tempIntegarl   = 0;          // 当前局积分
        this.conn           = null;       // 连接对象
        this.ip             = "";         // 玩家IP
        this.player         = null;       // 玩家信息
        this.handsPokers    = new HandCards();// 玩家手牌
        this.totalBomb      = 0;          // 出炸弹的总次数
        this.totalCoverBomb = 0;          // 被炸的总次数
        this.totalCatchPock = 0;          // 捉麻子总次数
        this.totalCoverCatchPock = 0;     // 被捉麻子总次数
        this.totalSurplusCardNum = 0;     // 总剩余牌数量

        this.online         = false;      // 是否在线
        this.hangPackets    = [];         // 挂起等待发送的数据包

        this.marks          = [];         // 标志
        this.isNullBomb     = false;      // 是否空炸
        this.isNotUseBomb   = false;      // 玩家是否不能使用炸弹
        this.isDischargeWater= false;     // 玩家是否作弊
        this.tempScore      = 0;          // 当前局牌分数
        this.tmepdischargeWaterNum = 0;   // 放水积分
        this.isOffTwo       = false;      // 是否有关2
    }
};
exports.Player = Player;

/*

var card1 = [
    {"type":3,"num":3,"red":1,"black": 1,"block":1,"plum":0},
    {"type":4,"num":3,"red":1,"black":1,"block":1,"plum":0},
    {"type":5,"num":3,"red":1,"black":1,"block":1,"plum":0},
    {"type":6,"num":1,"red":1,"black":0,"block":0,"plum":0},
    {"type":7,"num":1,"red":1,"black":0,"block":0,"plum":0},
    {"type":8,"num":1,"red":1,"black":0,"block": 0,"plum":0},
    {"type":9,"num":0,"red":0,"black":0,"block":0,"plum":0},
    {"type":10,"num":0,"red":0,"black":0,"block":0,"plum":0},
    {"type":11,"num":0,"red":0,"black":1,"block":0,"plum":0},
    {"type":12,"num":1,"red":0,"black":0,"block":0,"plum":1},
    {"type":13,"num":1,"red":0,"black":0,"block":0,"plum":1},
    {"type":1,"num":1,"red":0,"black":0,"block":0,"plum":1},
    {"type":2,"num":1,"red":1,"black":0,"block":0,"plum":0},

];

var card2 = [
    {"type":3,"num":1,"red":0,"black":0,"block":0,"plum":1},
    {"type":4,"num":1,"red":0,"black":0,"block":0,"plum":1},
    {"type":5,"num":1,"red":0,"black":0,"block":0,"plum":1},
    {"type":6,"num":0,"red":0,"black":0,"block":0,"plum":0},
    {"type":7,"num":0,"red":0,"black":0,"block":0,"plum":0},
    {"type":8,"num":1,"red":0,"black":0,"block":0,"plum":1},
    {"type":9,"num":1,"red":0,"black":0,"block":1,"plum":1},
    {"type":10,"num":1,"red":1,"black":0,"block":0,"plum":0},
    {"type":11,"num":1,"red":1,"black":0,"block":0,"plum":1},
    {"type":12,"num":3,"red":1,"black":1,"block":1,"plum":0},
    {"type":13,"num":3,"red":1,"black":1,"block":1,"plum":0},
    {"type":1,"num":3,"red":1,"black":1,"block":1,"plum":0},
    {"type":2,"num":0,"red":0,"black":0,"block":0,"plum":0},
];
var card3 = [
    {"type":3,"num":0,"red":0,"black":0,"block":0,"plum":0,},
    {"type":4,"num":0,"red":0,"black":0,"block":0,"plum":0},
    {"type":5,"num":0,"red":0,"black":0,"block":0,"plum":0},
    {"type":6,"num":3,"red":1,"black":1,"block":1,"plum":0},
    {"type":7,"num":3,"red":1,"black":1,"block":1,"plum":0},
    {"type":8,"num":2,"red":0,"black":1,"block":1,"plum":0},
    {"type":9,"num":3,"red":1,"black":1,"block":1,"plum":0},
    {"type":10,"num":3,"red":1,"black":1,"block":1,"plum":0},
    {"type":11,"num":3,"red":1,"black":1,"block":1,"plum":0},
    {"type":12,"num":0,"red":0,"black":0,"block":0,"plum":0},
    {"type":13,"num":0,"red":1,"black":1,"block":1,"plum":1},
    {"type":1,"num":0,"red":1,"black":1,"block":1,"plum":1},
    {"type":2,"num":0,"red":0,"black":0,"block":0,"plum":0},
];

if( flag == 1){
    _me.cards = card1;
}else if ( flag == 2){
    _me.cards = card2;
}else {
    _me.cards = card3;
}
_me.num = 16;
*/
